<template>
    <div class="main-container flex min-h-[300px]" v-loading="loading" >
        <div class="main-body flex-1 mr-[15px]" :class="!loading ? '' : 'hidden'">
            <el-card class="box-card !border-none" shadow="never" >
                <div class="flex justify-between items-center">
					<div class="flex">
						<div>
							<img v-if="statInfo.site_info.icon" class="w-[50px] h-[50px]" :src="img(statInfo.site_info.icon)"/>
							<img v-else class="w-[50px] h-[50px]" src="@/assets/images/index/site_img.png"/>
						</div>
						<div class="ml-[12px]">
							<div>
								<span class="font-bold text-[18px]">{{ statInfo.site_info.site_name }}</span>
								<span class="text-[12px] ml-[12px]">ID:{{ statInfo.site_info.site_id }}</span>
							</div>
							<div>
								<span class="text-[14px] text-[#666] mr-[12px]">{{ t('siteType') }}：{{ statInfo.site_info.group_name }}</span>
								<span v-if="statInfo.site_info.status == 1" class="text-[10px] py-[3px] px-[10px] bg-[#E6EFFF] text-[#2D5FFF] rounded-[3px]">{{ statInfo.site_info.status_name }}</span>
								<span v-else class="text-[10px] py-[3px] px-[10px] bg-[#FFE6E9] text-[#FF2D2D] rounded-[3px]">{{ statInfo.site_info.status_name }}</span>
							</div>
						</div>
					</div>
					<div class="flex">
						<div>
							<div><span class="text-[14px] text-[#666]">{{ t('periodTime') }}：{{ statInfo.site_info.create_time ? statInfo.site_info.create_time.split(' ')[0] : '' }} / {{ statInfo.site_info.expire_time ? statInfo.site_info.expire_time.split(' ')[0] : '' }}</span></div>
							<div class="w-[225px] h-[12px] bg-[#E6EFFF] rounded-[999px] mt-1">
								<div class="bg-primary site-date rounded-[999px] h-[12px]" :style="{width: statInfo.site_info.mix}"></div>
							</div>
						</div>
						<div class="ml-[40px]">
							<el-button v-if="statInfo.site_info.over_date <= 7" class="bottom-back w-[80px] h-[40px] text-[14px] bg-transparent" type="primary" plain @click="renew">{{ t('renew') }}</el-button>
							<el-button class="w-[80px] h-[40px] text-[14px]" type="primary" >{{ t('accessSite') }}</el-button>
						</div>
					</div>
				</div>
				<div class="mt-[60px]"  v-if="!loading">
					<div class="card-header flex justify-between border-b-[1px] border-[#EBEBEC] pb-[15px]">
					    <span class="text-[18px]">{{t('appTemplate')}}</span>
						<div @click="optionModel" v-if="!edit_menu" class="cursor-pointer">
							<img class="w-[15px]" src="@/assets/images/index/edit.png"/>
						</div>
						<div v-if="edit_menu">
							<el-button type="primary" @click="primary">{{ t('complete') }}</el-button>
						</div>
					</div>
					<div class="flex flex-wrap">
						<div class="flex flex-wrap" ref="shortcutModel" v-if="edit_menu">
							<div v-for="(items, index) in shortcut_menu" :style="{backgroundColor : items.bg_color}" :key="items.id" class="design-field w-[180px] h-[120px] relative mt-[30px] rounded-[5px] mr-[30px] cursor-pointer">
								<div class="flex items-center h-[88px]" @click="editModel(items)">
									<!-- <img class="ml-[24px] w-[40px]" :src="img(items.img)"/> -->
									<div class="ml-[24px] w-[40px]">
										<icon :name="items.img" size="40px" color="#fff"></icon>
									</div>
									<span class="text-item text-[16px] text-[#fff] ml-[12px] max-w-[120px]">{{ items.name }}</span>
								</div>
								<div class="item-bottom h-[32px] leading-[32px] text-center" @click="editModel(items)">
									<span class="text-item text-[12px] text-[#fff] max-w-[150px]">{{ items.desc }}</span>
								</div>
								<div class="delete-item absolute w-[20px] h-[20px] rounded-[999px] overflow-hidden" v-if="edit_menu" @click="removeMenu(items)">
									<img class="w-[20px] h-[20px]" src="@/assets/images/index/del_model.png"/>
								</div>
							</div>
						</div>
						<div v-else class="flex flex-wrap">
							<div v-for="(items, index) in shortcut_menu" :style="{backgroundColor : items.bg_color}" class="w-[180px] h-[120px] relative mt-[30px] rounded-[5px] overflow-hidden mr-[30px] cursor-pointer">
								<div class="flex items-center h-[88px]" @click="toLink(items.router_path)">
									<!-- <img class="" :src="img(items.img)"/> -->
									<div class="ml-[24px] w-[40px]">
										<icon :name="items.img" size="40px" color="#fff"></icon>
									</div>
									<span class="text-item text-[16px] text-[#fff] ml-[12px] max-w-[120px]">{{ items.name }}</span>
								</div>
								<div class="item-bottom h-[32px] leading-[32px] text-center"  @click="toLink(items.router_path)">
									<span class="text-item text-[12px] text-[#fff] max-w-[150px]">{{ items.desc }}</span>
								</div>
							</div>
						</div>
						<div v-if="edit_menu" class="w-[180px] h-[120px] mt-[30px] rounded-[5px] overflow-hidden border-dashed border-[1px] border-[#D0D7D9] cursor-pointer" @click="showFromMenu">
							<div class="w-[40px] mx-auto mt-[20px]"><img class="w-[40px]" src="@/assets/images/index/add_menu.png" /></div>
							<p class="text-center mt-[5px] text-[20px]">{{ t('addMenu') }}</p>
						</div>
						<div v-if="shortcut_menu.length <= 0 && !edit_menu" class="flex w-full justify-center items-center min-w-[1000px] min-h-[400px]">
							<div v-if="!loading">
								<img src="@/assets/images/empty.png"/>
								<p class="text-center text-gray-400">{{ t('emptyMenu') }}</p>
							</div>
						</div>
					</div>
				</div>
            </el-card>
        </div>
		<el-dialog v-model="shortcutMenu" :title="t('addShortcutMenu')" width="500px" :destroy-on-close="true">
			<el-form :model="formData" label-width="90px" ref="formRef" :rules="formRules" class="page-form" v-loading="loading">
				
				<el-form-item :label="t('menuName')" prop="name">
				    <el-input v-model="formData.name" clearable class="w-[245px]" :placeholder="t('menuNamePlaceholder')" />
				</el-form-item>
				
				<el-form-item :label="t('path')" prop="router_path">
					<div class="w-[245px]">
						<el-input v-if="!model_show" v-model="formData.router_path" clearable class="w-[245px]" placeholder="https://"/>
						<div v-else>
							<span class="bg-primary py-[5px] px-[10px] text-[#fff] relative rounded-[3px]">
								{{ formData.link_name }}
								<span class="absolute top-[-5px] right-[-5px] cursor-pointer" @click="deleteMenu">
									<img class="w-[15px] h-[15px]" src="@/assets/images/index/del_model.png"/>
								</span>
							</span>
						</div>
					</div>
					<el-button class="model-btn ml-[10px] text-[14px]" type="primary" @click="showMenu = true">{{ t('selectModel') }}</el-button>
				</el-form-item>
			
			    <el-form-item :label="t('menuBgColor')" prop="bg_color">
					<div class="flex items-center">
						<div class="mr-[8px] p-[4px] rounded-[99px]" :class="formData.bg_color == '#6F77FF' ? 'border-[1px] border-[##DCDFE6]' : '' ">
							<div @click="formData.bg_color = '#6F77FF'" class="w-[20px] h-[20px] cursor-pointer bg-[#6F77FF] rounded-[99px]"></div>
						</div>
						<div class="mr-[8px] p-[4px] rounded-[99px]" :class="formData.bg_color == '#0FB199' ? 'border-[1px] border-[##DCDFE6' : '' ">
							<div @click="formData.bg_color = '#0FB199'" class="w-[20px] h-[20px] cursor-pointer bg-[#0FB199] rounded-[99px]"></div>
						</div>
						<div class="mr-[8px] p-[4px] rounded-[99px]" :class="formData.bg_color == '#FFA238' ? 'border-[1px] border-[##DCDFE6]' : '' ">
							<div @click="formData.bg_color = '#FFA238'" class="w-[20px] h-[20px] cursor-pointer bg-[#FFA238] rounded-[99px]"></div>
						</div>
						<div class="mr-[8px] p-[4px] rounded-[99px]" :class="formData.bg_color == '#4A78FF' ? 'border-[1px] border-[##DCDFE6]' : '' ">
							<div @click="formData.bg_color = '#4A78FF'" class="w-[20px] h-[20px] cursor-pointer bg-[#4A78FF] rounded-[99px]"></div>
						</div>
						<div class="mr-[8px] p-[4px] rounded-[99px]" :class="formData.bg_color == '#FE5858' ? 'border-[1px] border-[##DCDFE6]' : '' ">
							<div @click="formData.bg_color = '#FE5858'" class="w-[20px] h-[20px] cursor-pointer bg-[#FE5858] rounded-[99px]"></div>
						</div>
						<div class="mr-[8px] p-[4px] rounded-[99px]" :class="formData.bg_color == '#6EB44E' ? 'border-[1px] border-[##DCDFE6]' : '' ">
							<div @click="formData.bg_color = '#6EB44E'" class="w-[20px] h-[20px] cursor-pointer bg-[#6EB44E] rounded-[99px]"></div>
						</div>
						<div class="mr-[8px] p-[4px] rounded-[99px]" :class="formData.bg_color == '#FA6400' ? 'border-[1px] border-[##DCDFE6]' : '' ">
							<div @click="formData.bg_color = '#FA6400'" class="w-[20px] h-[20px] cursor-pointer bg-[#FA6400] rounded-[99px]"></div>
						</div>
						<el-color-picker v-model="formData.bg_color" show-alpha />
					</div>
			    </el-form-item>
			
			    <el-form-item :label="t('menuImg')" prop="icon">
					<select-icon v-model="formData.img" />
			    </el-form-item>
			    
			    <el-form-item :label="t('menuDesc')">
			        <el-input v-model="formData.desc" :placeholder="t('descPlaceholder')" clearable class="w-[245px]" />
			    </el-form-item>
			
			</el-form>
		    <template #footer>
		        <span class="dialog-footer">
		            <el-button type="primary" @click="addShortcut(formRef)">{{t('confirm')}}</el-button>
		        </span>
		    </template>
		</el-dialog>
		<el-dialog v-model="renewDialog" :title="t('message')" width="500px" :destroy-on-close="true">
			<div class="flex mt-1">
				<div class="mr-[30px] flex">
					<icon name="iconfont-icondianhua" class="leading-[1]" size="20px" color="#000"></icon>
					<p class="text-[14px] ml-2">{{ t('tel') }}</p>
				</div>
				<div>
				    <p class="text-[14px]">{{ serviceData.tel }}</p>
				</div>
			</div>
		    <template #footer>
		        <span class="dialog-footer">
		            <el-button type="primary" @click="renewDialog = false">{{t('confirm')}}</el-button>
		        </span>
		    </template>
		</el-dialog>
		<el-dialog v-model="showMenu" :title="t('pathSelect')" width="500px" :destroy-on-close="true">
			<div class="flex mt-1 flex-wrap">
				<el-button v-for="item in menu_list" class="menu-btn mb-[5px] mr-[10px] ml-[0px]" @click="selectMenu(item)">{{ item.menu_name }}</el-button>
			</div>
		</el-dialog>
		<el-dialog v-model="customPath" width="500px" :destroy-on-close="true">
			<el-form :model="formData" label-width="90px" ref="formRef" class="page-form">
			    <el-form-item :label="t('shortcutLink')">
			        <el-input v-model="formData.router_path" clearable class="input-width" />
			    </el-form-item>
			</el-form>
		    <template #footer>
		        <span class="dialog-footer">
		            <el-button type="primary" @click="customPath = false">{{t('confirm')}}</el-button>
		        </span>
		    </template>
		</el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, nextTick } from 'vue'
import { t } from '@/lang'
import { getSiteStatInfo } from '@/api/stat'
import { getService, getShortcutMenu, setShortcutMenu, getAuthMenu } from '@/api/sys'
import { range } from 'lodash-es'
import { img } from '@/utils/common'
import Sortable, { SortableEvent } from 'sortablejs'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'

const renewDialog = ref(false)
const renew = () => {
  renewDialog.value = true
}

const loading = ref(true)

let statInfo = ref({'today_data':{},system:{},version:{},about:[],visit_stat:{},member_stat:{},site_info:{},total_data:{}})
const getStatInfoFn = async (id: number = 0) => {
    statInfo.value = await (await getSiteStatInfo()).data
}
getStatInfoFn()

const router = useRouter()
/**
 * 链接跳转
 */
const toLink = (link) => {
    router.push("/"+link)
}

const initialFormData = {
	id: 0,
	name: '',
	bg_color: '',
	img: '',
	desc: '',
	link_name: '',
	router_path: '',
	menu_key: ''
}
const formData: Record<string, any> = reactive({ ...initialFormData })

const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = computed(() => {
    return {
        name: [
            { required: true, message: t('menuNamePlaceholder'), trigger: 'blur' },
        ],
        bg_color: [
            { required: true, message: t('bgColorPlaceholder'), trigger: 'blur' },
        ],
        icon: [
            { required: true, validator: iconPass, trigger: 'blur' }
        ],
        router_path: [
            { required: true, validator: pathPass, trigger: 'blur' },
        ]
    }
})

const iconPass = (rule: any, value: any, callback: any) => {
	if(formData.img == ''){
		callback(new Error(t('iconPlaceholder')))
	}
	callback()
}
const pathPass = (rule: any, value: any, callback: any) => {
	if(formData.router_path == ''){
		callback(new Error(t('pathPlaceholder')))
	}
	callback()
}

const shortcutMenu = ref(false)
const edit_menu = ref(false)
const customPath = ref(false)
const showMenu = ref(false)
const shortcut_menu = ref([]);
const menu_list = ref()
const is_remove = ref(false)
const model_show = ref(false)
const checkMenu = () => {
	getShortcutMenu().then(res=>{
		shortcut_menu.value = res.data
		loading.value = false;
	})
}
checkMenu()
const addShortcut = async (formEl: FormInstance | undefined) => {
    if (loading.value || !formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
			let data = []
			if(shortcut_menu.value.length > 0){
				data = shortcut_menu.value
			}
			
			let time = parseInt(new Date().getTime() / 1000) + '';
			let num = Math.floor(Math.random() * (999 - 1) ) + 1;
			
			//如果是编辑，匹配原数据修改
			if(formData.id > 0){
				for(let i in data){
					if(data[i].id == formData.id){
						data[i].name = formData.name,
						data[i].bg_color = formData.bg_color,
						data[i].img = formData.img,
						data[i].desc = formData.desc,
						data[i].link_name = formData.link_name,
						data[i].router_path = formData.router_path,
						data[i].menu_key = formData.menu_key
					}
				}
			}else{
				data.push({
					id: formData.id > 0 ? formData.id : time+num,
					name: formData.name,
					bg_color: formData.bg_color,
					img: formData.img,
					desc: formData.desc,
					link_name: formData.link_name,
					router_path: formData.router_path,
					menu_key: formData.menu_key
				})
			}

			setShortcutMenu({
				menu: data
			}).then(() =>{
				shortcutMenu.value = false
				checkMenu()
			})
        }
    })
}

const editModel = (item) => {
	shortcutMenu.value = true
	formData.id = item.id,
	formData.name = item.name,
	formData.bg_color = item.bg_color,
	formData.img = item.img,
	formData.desc = item.desc,
	formData.link_name = item.link_name,
	formData.router_path = item.router_path,
	formData.menu_key = item.menu_key
	if(item.menu_key){
		model_show.value = true
	}
}

const removeMenu = (item) => {
	is_remove.value = true
	let menu_arr = shortcut_menu.value;
	for(let i in menu_arr){
		if(menu_arr[i].id == item.id){
			menu_arr.splice(i, 1)
		}
	}
	shortcut_menu.value = menu_arr;
}

const primary = () => {
	edit_menu.value = false;
	if(!is_remove.value) return
	setShortcutMenu({
		menu: shortcut_menu.value
	}).then(() =>{})
}
const showFromMenu = () =>{
	shortcutMenu.value = true
	model_show.value = false
	formData.name = ''
	formData.bg_color = ''
	formData.img = ''
	formData.desc = ''
	formData.link_name = ''
	formData.router_path = ''
	formData.menu_key = ''
} 
const checkMenuList = () => {
	getAuthMenu().then(res=> {
		menu_list.value = res.data
	})
}
checkMenuList()
const selectMenu = (item) => {
	formData.link_name = item.menu_name
	formData.router_path = item.router_path
	formData.menu_key = item.menu_key
	showMenu.value = false
	model_show.value = true
}
const shortcutModel = ref()
interface SortableEvt extends SortableEvent {
    originalEvent?: DragEvent
}

const deleteMenu = () => {
	model_show.value = false
	formData.link_name = ''
	formData.router_path = ''
	formData.menu_key = ''
}

const optionModel = () =>{
	edit_menu.value = true
	setTimeout(() => {
		const sortable = Sortable.create(shortcutModel.value, {
			ghostClass: '.design-field',
			animation: 200,
			onEnd: (evt) => {
				let arr = shortcut_menu.value[evt.oldIndex!];
				shortcut_menu.value.splice(evt.oldIndex!, 1)
				shortcut_menu.value.splice(evt.newIndex!, 0, arr)
				
				nextTick(() => {
				    sortable.sort(range(shortcut_menu.value.length).map((value) => value.toString()))
                    is_remove.value = true;
				})
			}
		})
	}, 500)
	
}

</script>

<style lang="scss" scoped>
.card-header > span{
    line-height: 21px;
}
.site-info {
	background-image: url('');
	background-size: 100% 100%;
}
.item-bottom {
	background-color: rgba(0, 0, 0, 0.10);
}
.bottom-back {
	background-color:rgba(255, 255, 255, 0);
	&:hover {
	    background-color: var(--el-color-primary);
	}
}
.delete-item {
	top: -8px;
	right: -8px;
	font-size: 20px;
}
.text-item{
	  overflow:hidden;
	  white-space: nowrap;
	  text-overflow: ellipsis;
	  -o-text-overflow:ellipsis;
}
.menu-btn {
	margin-left: 0px !important;
}
.model-btn {

	font-size: 14px;
	padding: 3px 6px;
}
.input-bg{
	background-color: #F2F4F6;
}
</style>
